import { Component, Injector, OnInit, ViewChild } from '@angular/core';
import { STColumn, STColumnTag, STData } from '@delon/abc/st';
import { SFComponent, SFRadioWidgetSchema, SFSchema, SFUISchema } from '@delon/form';
import { STComponentBase } from '@shared/itcore/components/st-component-base';
import { ItcoreSTColumn } from '@shared/itcore/services/alain.types';


@Component({
  selector: 'app-db-config',
  templateUrl: './config.component.html',
  styles: [
    `
    .db-expand-boxies{
      padding: 5px;
      font-size: 13px;
    line-height: 30px;
    }
    .db-expand-box span {
      padding-right:20px;
    }
    `
  ],
})
export class DbConfigComponent extends STComponentBase implements OnInit {

  constructor(injector: Injector) {
    super(injector);
    this.moduleName = 'DBConfig';
    this.isUserDrawer = true;
  }

  @ViewChild('sf', { static: false }) sf: SFComponent;

  areaName = 'db/';

  drawerCollectVisible = true;
  // 
  allTableList = [];
  ConfigType = [{ id: 1, text: '默认配置' }, { id: 2, text: '手动配置' }];
  ConfigTypeTags = { 1: { text: '默认配置', color: 'green' }, 2: { text: '手动配置', color: 'orange' } };

  // 分表维度
  DimensionTags: STColumnTag = {
    1: { text: '天', color: '#409eff' }
    , 2: { text: '月', color: '#67c23a' },
    3: { text: '季度', color: '#e6a23c' }
    , 4: { text: '年', color: '#f56c6c' }
  };
  StatusTags: STColumnTag = {
    10: { text: '启用', color: 'green' }
    , 20: { text: '暂停', color: 'orange' },
    '-10': { text: '禁用', color: 'red' }
  };

  ConfigStatus = [{ id: 10, text: '启用' }, { id: 20, text: '暂停' }, { id: -10, text: '禁用' }];

  ngOnInit() {
    super.InitBase();
  }
  protected GetSTColumns(): ItcoreSTColumn[] {
    return [
      {
        title: '操作',
        fixed: 'left',
        width: 65,
        buttons: [
          {
            text: '操作',
            children: [
              {
                text: '编辑',
                icon: 'edit',
                acl: 'Root.Db.Db.DBConfig.Update',
                click: (row) => this.edit(row),
              },
              {
                text: '删除',
                icon: 'delete',
                type: 'del',
                acl: 'Root.Db.Db.DBConfig.Delete',
                click: (row) => this.delete(row),
              },
            ],
          },
          {
            text: '启用',
            acl: 'Root.Db.Db.DBConfig.UpdateRunStatus',
            iif: (data, btn, column) => {
              return data.RunStatus !== 10;
            },
            click: (row) => this.changeRunStatus(row.Id, 10, row.RunStatus),
          },
          {
            text: '禁用',
            pop: {
              trigger: 'click',
              placement: 'top',
              title: '你确定要禁用吗？ 禁用后目前不能启用了~'
            },
            acl: 'Root.Db.Db.DBConfig.UpdateRunStatus',
            iif: (data, btn, column) => {
              return data.RunStatus !== -10;
            },
            click: (row) => this.changeRunStatus(row.Id, -10),
          },
          {
            text: '暂停',
            pop: {
              trigger: 'click',
              placement: 'top',
              title: '你确定要暂停吗？'
            },
            acl: 'Root.Db.Db.DBConfig.UpdateRunStatus',
            iif: (data, btn, column) => {
              return data.RunStatus === 10;
            },
            click: (row) => this.changeRunStatus(row.Id, 20),
          },
        ],
        required: ['ConfigName', 'ConfigType', 'FromDbConnectionId', 'ToDbConnectionId', 'SubTableDimension', 'TableNameEx', 'TimeConditionEx', 'SearchSql'],
      },

      { title: '配置名称', index: 'ConfigName', editable: true, sortNumber: 1, filterable: true, },
      {
        title: '配置类型', index: 'ConfigType', editable: true, sortNumber: 2, filterable: true,
        type: 'tag',
        tag: this.ConfigTypeTags,
        fenum: this.toEnum(this.ConfigType),
        fdefault: 1
      },

      {
        title: '目标数据库', index: 'ToDataBaseName', editable: true, sortNumber: 5, ftype: 'string',
        ui: {
          widget: 'select',
        },
      },
      { title: '执行时间段', index: 'RunPeriod', editable: true, default: '00:01,06:00', description: '配置执行的时间段，例如（00:01,06:00）', sortNumber: 10, },
      {
        title: '分表维度', index: 'SubTableDimension', editable: true, description: '选择维度单位，即每隔多少（天、月、季度、年）分一次表', filterable: true,
        fdefault: 2,
        type: 'tag',
        tag: this.DimensionTags,
        ui: {
          widget: 'radio',
          styleType: 'button',
          buttonStyle: 'solid',
          asyncData: () => this.alain.ReadNode('api/Db/DBConfig/GetEnumList?key=dimension', 'name', 'id'),
        } as SFRadioWidgetSchema,
        sortNumber: 6,
      },
      {
        title: '执行状态', index: 'RunStatus', editable: true, sortNumber: 6, fdefault: 20, filterable: true,
        type: 'tag',
        tag: this.StatusTags,
        IsHideEdit: true,
        ui: {
          widget: 'radio',
          styleType: 'button',
          buttonStyle: 'solid',
          asyncData: () => this.alain.ReadNode('api/Db/DBConfig/GetEnumList?key=runStatus', 'name', 'id'),
        } as SFRadioWidgetSchema,
      },
      { title: '运行间隔(秒)', index: 'RunTimeInterval', editable: true, ftype: 'number', default: '60', sortNumber: 6, description: '定时调度每次运行间隔，单位 秒' },

      {
        title: '备注', index: 'Remark', editable: true, sortNumber: 99, ui: {
          widget: 'textarea',
          autosize: { minRows: 2, maxRows: 6 },
        }
      },
      { title: '创建时间', index: 'CreatedTime', sort: true, type: 'date', filterable: true },
    ];
  }

  protected GetExpandSFSchema(): ItcoreSTColumn[] {
    return [
      {
        title: '源数据库连接', index: 'FromDbConnectionId', editable: true, sortNumber: 3,
        ui: {
          widget: 'itcore-db-connect',
          change: (value) => {
            const statusProperty = this.sf.getProperty('/TableNameEx');
            this.getHttpAllTableTree(value, () => {
              statusProperty.schema.enum = this.allTableList;
              statusProperty.widget.reset([]);
            });

            if (this.editRow) {
              const option = {
                ConnectId: value,
                DataBaseName: this.editRow.TableNameEx[0],
                TableName: this.editRow.TableNameEx[1]
              };
              this.refreshTimeConditionEx(option);
              this.refreshOrtherCondition(option);
              this.refreshKeyColumnPraerty(option);
            }
          }
        }
      },
      {
        title: '源数据表名', index: 'TableNameEx', editable: true, fenum: this.allTableList, sortNumber: 3, ui: {
          widget: 'cascader',
          change: (value) => {

            const fromDbConnectionId = this.sf.getValue('/FromDbConnectionId');
            const option = {
              ConnectId: fromDbConnectionId,
              DataBaseName: value[0],
              TableName: value[1]
            };

            this.refreshTimeConditionEx(option);
            this.refreshOrtherCondition(option);
            this.refreshKeyColumnPraerty(option);

          }
        },
      },
      {
        title: '目标数据库连接', index: 'ToDbConnectionId', editable: true, sortNumber: 4,
        ui: {
          widget: 'itcore-db-connect',
          change: (value) => {
            const databalseProperty = this.sf.getProperty('/ToDataBaseName');
            this.getHttpAllDatabase(value, (rdata) => {
              databalseProperty.schema.enum = rdata.map(x => {
                return { label: x, value: x };
              });
              databalseProperty.widget.reset(databalseProperty.formData);
            });
          }
        }
      },

      {
        title: '主键列', index: 'PrimaryKeyColumn', editable: true, description: '用于查询或者删除的主键列', sortNumber: 5,
        ui: {
          widget: 'select',
        }
      },
      {
        title: '时间条件', index: 'TimeConditionEx', editable: true, description: '指定备份的时间字段，手动填写sql的时候 天数可以不改', sortNumber: 5,
        visibleIf: { ConfigType: (value: any) => value === 2 },
        ui: {
          widget: 'itcore-db-column-filter',
          isSelectDate: true
        }
      },
      {
        title: '其他条件', index: 'OtherConditionEx', editable: true, sortNumber: 5,
        visibleIf: { ConfigType: (value: any) => value === 2 },
        ui: {
          widget: 'itcore-db-column-filter',
          isSelectDate: false
        }
      },
      { title: '每次最大条数', index: 'MaxCountOnce', editable: true, visibleIf: { ConfigType: (value: any) => value === 1 }, default: '1000', sortNumber: 5 },
      {
        title: '查询sql', index: 'SearchSql', editable: true, description: '自定义查询sql，请输入完整的，且有效的sql', sortNumber: 5, ui: {
          widget: 'textarea',
          autosize: { minRows: 2, maxRows: 6 },
        }
      },
    ];
  }

  // #endregion
  protected GetSFUISchema(): SFUISchema {
    const ui: SFUISchema = {
      '*': { spanLabelFixed: 150, grid: { span: 22 } },
      $TimeConditionEx: { grid: { span: 12 } },
      $OtherConditionEx: { grid: { span: 24 }, visibleIf: { ConfigType: (value: any) => value === 1 } },
      $MaxCountOnce: { visibleIf: { ConfigType: (value: any) => value === 1 } },
      $SearchSql: { visibleIf: { ConfigType: (value: any) => value === 2 } },
    };
    return ui;
  }

  getHttpAllTableTree(id, callback) {
    this.itcore.http.post('api/Db/Db/GetDataBaseNode', null, { collectId: id }).subscribe(res => {
      if (res.Type === 200) {
        this.allTableList = res.Data;
        callback();
      }
    });
  }
  getHttpAllDatabase(id, callback) {
    this.itcore.http.get('api/Db/Db/GetAllDataBase', { collectId: id }).subscribe(res => {
      if (res.Type === 200) {
        callback(res.Data);
      }
    });
  }

  changeRunStatus(configId, runstatus, oldrunsratus?) {

    if (oldrunsratus && oldrunsratus === -10) {
      this.itcore.msgSrv.error('禁用状态暂时不给启用~~');
      return;
    }

    this.itcore.http.post('api/Db/DBConfig/UpdateRunStatus', null, { id: configId, runstatus }).subscribe(res => {
      if (res.Type === 200) {
        this.itcore.msgSrv.success(res.Content);
        this.st.reload();
      } else {
        this.itcore.msgSrv.error(res.Content);
      }
    });
  }
  getHttpColumn(option, callback) {
    this.itcore.http.post('api/Db/Db/GetAllColumn', option).subscribe(res => {
      if (res.Type === 200) {
        callback(res.Data);
      }
    });
  }

  // 刷新 KeyColumnProperty  列
  refreshKeyColumnPraerty(option) {
    this.itcore.http.post('api/Db/Db/GetAllColumn', option).subscribe(res => {
      if (res.Type === 200) {
        const primaryKeyColumnProperty = this.sf.getProperty('/PrimaryKeyColumn');
        const data = res.Data;
        primaryKeyColumnProperty.schema.enum = data.map(x => {
          return { label: x.ColunmName, value: x.ColunmName };
        });
        primaryKeyColumnProperty.widget.reset(primaryKeyColumnProperty.formData);
      }
    });
  }
  // 刷新 时间条件
  refreshTimeConditionEx(option) {
    const timeConditionProperty = this.sf.getProperty('/TimeConditionEx');
    timeConditionProperty.ui.option = option;
    timeConditionProperty.widget.reset(option);
  }
  // 刷新其他条件
  refreshOrtherCondition(option) {
    const ortherConditionProperty = this.sf.getProperty('/OtherConditionEx');
    ortherConditionProperty.ui.option = option;
    ortherConditionProperty.widget.reset(option);
  }
}
